package com.yuanfeng.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.Json.JsonUtils;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.kuaidiniao.KdniaoTrackQueryAPI;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.goods.GoodsDetailsListVO;
import com.yuanfeng.commoms.vo.job.AcquiescenceVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.order.entity.OrderGoodsEntity;
import com.yuanfeng.order.feign.BaseServiceClient;
import com.yuanfeng.order.mapper.OrderGoodsMapper;
import com.yuanfeng.order.service.OrderGoodsService;
import com.yuanfeng.order.vo.GoodsParaVO;
import com.yuanfeng.order.vo.ManJianZengPinVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName OrderGoodsServiceImpl
 * @Description
 * @Author hyq
 * @Date 2023/6/21 10:40
 * @Version 1.0
 **/
@Service
public class OrderGoodsServiceImpl extends ServiceImpl<OrderGoodsMapper, OrderGoodsEntity>
        implements OrderGoodsService {

    @Autowired
    private BaseServiceClient baseServiceClient;

    private final Logger logger = LoggerFactory.getLogger(OrderGoodsServiceImpl.class);

    @Override
    public ResponseResult queryLogistics(Map<Object, Object> map) {
        String no = (String) map.get("no");
        if (StringUtils.isEmpty(no)) {
            return ResponseResult.fail(BizCodeEnume.ORDER_NUMBER_IS_EMPTY);
        }

        //查询订单信息
        List<OrderGoodsEntity> orderGoodsEntityList = this.baseMapper.selectList(new LambdaQueryWrapper<OrderGoodsEntity>()
                .select(OrderGoodsEntity::getOrderShippingCode,OrderGoodsEntity::getOrderShippingMessage)
                .eq(OrderGoodsEntity::getOrderId, no));
        //物流信息
        List<Map<String, Object>> returnStrs = new ArrayList<>();
        if (null != orderGoodsEntityList && !orderGoodsEntityList.isEmpty()) {
            //去重
            List<OrderGoodsEntity> shippingCodes = orderGoodsEntityList.stream().distinct().collect(Collectors.toList());
            for (OrderGoodsEntity shippinginfo : shippingCodes) {
                Map<String, Object> shippingMap = new HashMap<>();
                // 物流信息
                String returnStr = null;
                try {
                    String shippingCode = shippinginfo.getOrderShippingCode();
                    String shippingMessage = shippinginfo.getOrderShippingMessage();
                    List<OrderGoodsEntity> goodsList = this.baseMapper.selectList(new LambdaQueryWrapper<OrderGoodsEntity>()
                            .eq(OrderGoodsEntity::getOrderShippingCode, shippingCode)
                            .eq(OrderGoodsEntity::getOrderId, no));
                    System.out.println(goodsList);
                    if (!CollectionUtils.isEmpty(goodsList)) {
                        Map<String, String> resultMap = getShipperCode(goodsList);
                        System.out.println(resultMap);
                        //获取快递鸟的配置信息
                        KdniaoTrackQueryAPI.AppKey = resultMap.get("AppKey");
                        KdniaoTrackQueryAPI.EBusinessID = resultMap.get("EBussinessID");
                        KdniaoTrackQueryAPI.instructCode = String.valueOf(resultMap.get("instructCode"));
                        //获取快递的简称
                        String shipperCode = resultMap.get("shipperCode");
                        //获取收件人手机号后四位
                        String customerName = resultMap.get("customerName");

                        returnStr = KdniaoTrackQueryAPI.getOrderTracesByJson(shipperCode, shippingCode, customerName);

                        if (!StringUtils.isEmpty(returnStr)) {
                            shippingMap.put("shippingInfo", returnStr);
                            shippingMap.put("shippingMessage", shippingMessage);
                            shippingMap.put("expressName", resultMap.get("expressName"));
                            shippingMap.put("goodsList", goodsList);
                            shippingMap.put("shippingCode", shippingCode);
                            returnStrs.add(shippingMap);

                        }
                        logger.info("---------查询运单号为{}的物流信息结束,物流信息：{}", shippingCode, returnStr);
                    } else {
                        return ResponseResult.fail(BizCodeEnume.NO_INFORMATION_OBTAINED);
                    }

                } catch (Exception e) {
                    logger.info("queryLogisticsErrorResults:" + e.getMessage());
                    return ResponseResult.fail(e.getMessage());

                }
            }
        }
        return ResponseResult.success(returnStrs);
    }

    @Override
    public ResponseResult queryReturnGoods(Map<String, Object> map) {

        IPage<GoodsDetailsListVO> page=this.baseMapper.queryGoodsList2(new Query<GoodsDetailsListVO>().getPage(map),
                map);

        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult selectByPage(Map<String, Object> map) {
        HashMap<String, Object> returnMap = new HashMap<>();
        String orderId = String.valueOf(map.get("orderId"));
        IPage<GoodsDetailsListVO> page=this.baseMapper.queryGoodsListByPage(new Query<GoodsDetailsListVO>().getPage(map),
                map);
        //如果订单包含赠品 查询
        String giveawayInfo = this.baseMapper.queryOrderZengpinInfo(orderId);
        List<ManJianZengPinVO> list = new ArrayList<>();
        if(null != giveawayInfo && !"".equals(giveawayInfo)) {
            list = JsonUtils.string2Obj(giveawayInfo, List.class, ManJianZengPinVO.class);
        }
        //查询当前订单是否改价 如果 改价必须全单退
        Integer orderNum = this.baseMapper.queryOrderUpdatePrice(map);
        if(orderNum == 0 ){
            returnMap.put("updatePrice",false);
        }else{
            returnMap.put("updatePrice",true);
        }
        returnMap.put("orderGoods",PageUtils.getPage(page));
        returnMap.put("giveawayInfo",list);
        return ResponseResult.success(returnMap);
    }

    @Override
    public ResponseResult querySalesRanking(Map<String, Object> map) {
        String token = (String) map.get("token");
        UserInfoVO info = ParseTokenUtils.getPlatformUser(token);
        if (info != null) {
            try {
                Integer type = (Integer) map.get("type");
                List<GoodsParaVO> goodsList = null;
                if (type == 1) {
                    goodsList = this.baseMapper.queryAllGoods();
                } else if (type == 2) {
                    goodsList = this.baseMapper.queryTodayGoods();
                } else if (type == 3) {
                    goodsList = this.baseMapper.queryWeekGoods();
                } else if (type == 4) {
                    goodsList = this.baseMapper.queryMonthGoods();
                } else {
                    goodsList = this.baseMapper.queryYearGoods();
                }
                return ResponseResult.success(goodsList);
            } catch (Exception e) {
                return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(),BizCodeEnume.SYSTEM_ERROR.getMsg());
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
    }

    @Override
    public List<AcquiescenceVO> queryGoodsInfoByjob(String orderId) {
        List<OrderGoodsEntity> list=this.baseMapper.selectList(new LambdaQueryWrapper<OrderGoodsEntity>()
                .eq(OrderGoodsEntity::getOrderId,orderId));
        List<AcquiescenceVO> voList=new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)){
            for (OrderGoodsEntity entity:list) {
                AcquiescenceVO vo=new AcquiescenceVO();
                vo.setGoodsId(entity.getGoodsId());
                vo.setCommonId(entity.getCommonId());
                vo.setGoodsName(entity.getGoodsName());
                vo.setGoodsSpec(entity.getOrderSpecChineseValue());
                voList.add(vo);
            }
        }
        return voList;
    }

    public Map<String, String> getShipperCode(List<OrderGoodsEntity> goodsList) {
        Map map = new HashMap();
        //获取快递简称
        Integer orderShippingExpressId = goodsList.get(0).getOrderShippingExpressId();
        ResponseResult shipperResp = baseServiceClient.getBaseExpressInfoById(orderShippingExpressId);
        Map<String, String> shipperCode = JSONObject.parseObject(JSON.toJSONString(shipperResp.getData()), Map.class);
        map.put("shipperCode", shipperCode.get("expressPinyin"));
        map.put("expressName", shipperCode.get("expressName"));
        //获取快递鸟的配置
        Map<String, String> expressQueryByKdniao = (Map<String, String>) baseServiceClient.queryConfigFeign().getData();
        map.put("AppKey", expressQueryByKdniao.get("appkey"));
        map.put("EBussinessID", expressQueryByKdniao.get("ebussinessid"));
        map.put("instructCode", expressQueryByKdniao.get("instructCode"));
        //获取收件人手机号的后4位
        String orderReceiverContact = goodsList.get(0).getOrderSellerContact();
        String customerName = orderReceiverContact.substring(orderReceiverContact.length() - 4);

        map.put("customerName", customerName);

        return map;
    }
}
